package com.lee.utils;

import com.google.common.base.Joiner;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;


/**
 * @description TODO
 * @author Boomlee
 * @date 2022/12/27 16:23
 */



public class SqlUtils {


    /**
     * 根据数据库表名查询字段，拼接查询sql
     *
     * @param tableInfo dbname.tableName
     * @param conn      hive con
     * @return select a,b,c from A
     */
    public static String getSelectSql(String tableInfo, Connection conn) {
        String result;
        try {
            ResultSet resultSet = conn.createStatement().executeQuery("desc " + tableInfo);
            ArrayList<String> columnList = new ArrayList<>();
            while (resultSet.next()) {
                String c1 = resultSet.getString(1);
                columnList.add("`" + c1 + "`");
            }
            result = Joiner.on(",\n ").join(columnList);
            return "SELECT \n " + result + " \nFROM \n " + "`" + tableInfo + "`";
        } catch (Exception e) {
            return "异常";
        }
    }

    public static Long getColumnoCount(String tableInfo, Connection conn) throws SQLException {

        ResultSet resultSet = conn.createStatement().executeQuery("desc " + tableInfo);
        ArrayList<String> columnList = new ArrayList<>();
        while (resultSet.next()) {
            String c1 = resultSet.getString(1);
            columnList.add("`" + c1 + "`");
        }

        return (long) columnList.size();

    }
}
